<template>
    <div class="card-box" style="width: 600px">
        <a-typography-title :style="{ fontsize: '1220px' }">个人中心</a-typography-title>
        <a-divider />
        <a-typography-text :style="{ fontsize: '1220px' }">个人资料</a-typography-text>
        <a-divider />
        <div class="form-box" style="display: flex;">
            <div class="form-box-left">
                <div class="form-label">
                    <div style="width: 80px;"> <a-typography-text>昵称</a-typography-text></div>
                    <div style="margin-left: 20px;"></div>
                    <a-input v-model="form.nike_name" :style="{ width: '220px' }" default-value="" placeholder="" />
                </div>

                <div class="form-label">
                    <div style="width: 80px;"> <a-typography-text>邮箱</a-typography-text></div>
                    <div style="margin-left: 20px;"></div>
                    <a-input v-model="form.email" :style="{ width: '220px' }" default-value="" placeholder="" />
                </div>
            </div>

            <div class="form-box-right" style="margin-left: 200px;">
                <a-space direction="vertical" :style="{ width: '100%' }">
                    <a-upload action="/" :fileList="file ? [file] : []" :show-file-list="false" @change="onChange"
                        @progress="onProgress">
                        <template #upload-button>
                            <div :class="`arco-upload-list-item${file && file.status === 'error' ? ' arco-upload-list-item-error' : ''
                                }`">
                                <div class="arco-upload-list-picture custom-upload-avatar" v-if="file && file.url">
                                    <img :src="file.url" />
                                    <div class="arco-upload-list-picture-mask">
                                        <IconEdit />
                                    </div>
                                    <a-progress v-if="file.status === 'uploading' && file.percent < 100"
                                        :percent="file.percent" type="circle" size="mini" :style="{
                                            position: 'absolute',
                                            left: '50%',
                                            top: '50%',
                                            transform: 'translateX(-50%) translateY(-50%)',
                                        }" />
                                </div>
                                <div class="arco-upload-picture-card" v-else>
                                    <div class="arco-upload-picture-card-text">
                                        <IconPlus />
                                        <div style="margin-top: 10px; font-weight: 600">Upload</div>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </a-upload>
                </a-space>
                <div style="margin-left: 10px;">
                    <a-typography-text>更换头像</a-typography-text>
                </div>
            </div>
        </div>

        <div style="margin-left: 50% ; margin-top: 10%;">
            <a-button type="primary" status="success" @click="submit()">保存修改</a-button>
        </div>
    </div>
</template>
  
<script>
import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon';
import { ref } from 'vue';
import * as qiniu from 'qiniu-js'
import http from '@/main';
import store from '@/store';
import { reactive } from 'vue';
import { Message } from '@arco-design/web-vue';


export default {
    components: { IconPlus, IconEdit },
    setup() {
        const file = ref();
        const token = ref('');
        let form = reactive({
            nike_name: null,
            email: null,
        })

        const onChange = (_, currentFile) => {
            file.value = {
                ...currentFile,
                // url: URL.createObjectURL(currentFile.file),
            };
        };
        const onProgress = (currentFile) => {
            file.value = currentFile;
        };

        const submit = () => {
            // 获取后端token
            http.get('/getToken')
                .then(res => {
                    token.value = res.data; // 图床token
                    console.log(token.value)

                    let authorization_text = "Bearer " + localStorage.getItem('token');
                    const post_config = {
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': authorization_text
                        },
                    }

                    const data = {
                        "age": null,
                        "articleCount": null,
                        "email": form.email,
                        "followers": null,
                        "gender": null,
                        "id": store.state.user.id,
                        "name": null,
                        "picture": null,
                        "subscribes": null,
                        "nickName": "form.nike_name"
                    }

                    const observer = {
                        next(res) {
                            console.log(res)
                        },
                        error() { },
                        complete(cpl) {
                            // 获得上传成功后的key(url) --> 成功之后的回调函数走这
                            console.log(cpl)
                            let reaback_url = "http://down.jiwaicat.top/" + cpl.key;

                            const newData = {
                                ...data,
                                'picture': reaback_url
                            }
                            // 更新用户信息
                            http.put('/users/auth/' + store.state.user.id, newData, post_config)
                                .then(() => {
                                    Message.info({ content: "更新成功 ", showIcon: true });
                                    store.state.user.picture = reaback_url;
                                })
                            // .catch(() => {
                            //     Message.err({ content: "服务错误，更新失败 ", showIcon: true });
                            // })
                        }
                    }

                    const putExtra = {
                        fname: "qiniu.png",
                        mimeType: "image/png",
                    };

                    const config = {
                        useCdnDomain: true,
                        region: qiniu.region.z2
                    }

                    // 上传图片
                    if (file.value != undefined) {
                        const observable = qiniu.upload(file.value.file, null, token.value, putExtra, config)
                        const subscription = observable.subscribe(observer) // 上传开始
                        console.log(subscription)
                        // 上传完成的回调函数是observer对象的compelete方法，跳到那去
                    } else {
                        // 不更新头像
                        http.put('/users/auth/' + store.state.user.id, data, post_config)
                            .then(() => {
                                Message.info({ content: "更新成功 ", showIcon: true });

                            })
                    }

                })

        }


        return {
            file, onChange, onProgress, token, submit, form
        }
    },
};
</script>


<style scoped>
.form-label {
    display: flex;
    margin-bottom: 20px;
}
</style>
  